﻿namespace SFWS.XHandler.Core
{
    using SFWS.XHandler.Core.Properties;
    using System;
    using System.Web;
    using System.Web.SessionState;
      

    public sealed class HandlerDo : IHttpHandler, IRequiresSessionState
    {
        private System.Resources.ResourceManager rm; 

        private HttpContext Context = null;

        private void Process(HttpContext context)
        {
            this.Context = context;
            object[] currentMapping = Mapping.Current.CurrentMapping;
            Type type = (currentMapping == null) ? null : ((Type) currentMapping[1]);
            if (type == null)
            {
                AppUtility.Log("404");
                AppUtility.Notify404();
            }
            else
            {
                IHttpHandler handler;
                try
                {
                    handler = (IHttpHandler) type.GetConstructor(Type.EmptyTypes).Invoke(null);
                }
                catch
                {
                    AppUtility.Log("404");
                    AppUtility.Notify404();
                    return;
                }
                if (!((this.IsLogined || AppUtility.IsLoginExclude(type)) || ((MappingNode) currentMapping[0]).IsLoginExclude))
                {
                    AppUtility.Log("000");
                    AppUtility.NotifyLogin();
                }
                else
                {
                    string str = AppUtility.ContextValidate(context, type);
                    if (!string.IsNullOrEmpty(str))
                    {
                        AppUtility.Log("403");
                        AppUtility.NotifyErrorStatus(0x193, str);
                    }
                    else
                    {
                        AppUtility.Log(context.Response.StatusCode.ToString());
                        handler.ProcessRequest(context);
                    }
                }
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (!context.Request.Path.ToLower().EndsWith(AppUtility.GetConfValue(Resources.ConfSectionName, Resources.ConfKey_PathSuffix).ToLower()))
            {
                AppUtility.Notify404();
            }
            else
            {
                this.Process(context);
            }
        }

        private bool IsLogined
        {
            get
            {
                try
                {
                    return (this.Context.Session[AppUtility.GetConfValue(Resources.ConfSectionName, Resources.ConfKey_IsLoginedSessionName) ?? Resources.IsLoginedSessionName] != null);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

